<script lang="ts" setup>
import { ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { getAdminInfoApi, storeAdminApi, updateAdminApi } from '#/api';

defineOptions({
  name: 'FormDrawer',
});

const gridApi = ref();
const record = ref();

const [Form, formApi] = useVbenForm({
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入管理员名称',
      },
      fieldName: 'name',
      label: '管理员名称',
      rules: 'required',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入管理员账号',
      },
      fieldName: 'account',
      label: '管理员账号',
      rules: 'required',
    },
    {
      component: 'Select',
      componentProps: {
        placeholder: '请输入管理员账号',
        class: 'w-full',
        mode: 'multiple',
      },
      fieldName: 'roles',
      label: '角色组',
      rules: 'required',
    },
    {
      component: 'RadioGroup',
      componentProps: {
        options: [
          {
            label: '正常',
            value: 1,
          },
          {
            label: '禁用',
            value: 0,
          },
        ],
      },
      defaultValue: 1,
      fieldName: 'status',
      label: '状态',
    },
  ],
  showDefaultActions: false,
});
const [Drawer, drawerApi] = useVbenDrawer({
  // 取消按钮
  onCancel() {
    drawerApi.close();
  },
  // 确认提交
  onConfirm() {
    formApi.validate().then(async (result) => {
      if (result.valid) {
        const data = await formApi.getValues();
        const id = record.value.id;
        const Api = id ? updateAdminApi(id, data) : storeAdminApi(data);
        Api.then((res) => {
          message.success('操作成功');
          gridApi.value?.reload();
          drawerApi.close();
        });
      }
    });
  },
  // 打开抽屉回调
  onOpenChange(isOpen: boolean) {
    record.value = isOpen ? drawerApi.getData()?.record || {} : {};
    gridApi.value = isOpen ? drawerApi.getData()?.gridApi : null;
    if (isOpen && record.value.id) {
      getAdminInfoApi(record.value.id).then((data) => {
        formApi.setValues(data);
      });
    }
  },
});
</script>

<template>
  <Drawer>
    <Form />
  </Drawer>
</template>
